import Vue from 'vue'
import VueRouter from 'vue-router'
import Home from '../views/Home.vue'
import Index from '../views/Index.vue'
import User from "../views/sys/User.vue";
import Menu from "../views/sys/Menu.vue";
import Role from "../views/sys/Role.vue";
import Student from "../views/sys/Student.vue";

import axios from "axios";
import store from "../store"

Vue.use(VueRouter)

const routes = [
  {
    path: '/',
    name: 'Home',
    component: Home,
    children: [
      {
        path: '/sys/index',
        name: 'Index',
        component: Index
      },
      {
        path: '/sys/users',
        name: 'SysUser',
        component: User
      },{
        path: '/userCenter',
        name: 'UserCenter',
        component: () => import('@/views/UserCenter.vue')
      },{
        path: '/sys/roles',
        name: 'SysRole',
        component: Role
      },{
        path: '/sys/menus',
        name: 'SysMenu',
        component: Menu
      },{
        path: '/sys/student',
        name: 'SysStudent',
        component: Student
      },
      {path: '/', redirect: '/login'},// 如果访问的是 localhost: 8080 则跳转到login页
    ]
  },
  {
    path: '/login',
    name: 'Login',
    // route level code-splitting
    // this generates a separate chunk (about.[hash].js) for this route
    // which is lazy-loaded when the route is visited.
    component: () => import('../views/Login.vue')
  }
]

const router = new VueRouter({
  mode: 'history',
  base: process.env.BASE_URL,
  routes
})

router.beforeEach(((to, from, next) => {
// to 是将要访问的路由的信息对象
// form 是将要离开的路由信息对象
// next 是一个函数，调用 next() 表示放行，允许这次路由导航
  // console.log(to)
  let hasRoute = store.state.menus.hasRoutes
  if (!hasRoute){
    axios.get("/sys/menu/nav",{
      headers: {
        Authorization: localStorage.getItem("token")
      }
    }).then(res =>{

      //拿到menuList
      store.commit("setMenuList",res.data.data.nav)
      //拿到用户权限
      store.commit("setPermList",res.data.data.authoritys)


      let newRoutes = router.options.routes

      res.data.data.nav.forEach(menu => {
        if (menu.children){
          menu.children.forEach(e =>{

            //转换成路由
            let route = menuToRoute(e)
            //把路由添加到路由管理中
            if (route){
              newRoutes[0].children.push(route)
            }
          })
        }
      })

      router.addRoutes(newRoutes)

      hasRoute = true
      store.commit("",hasRoute)
    })
  }
 
  next()
}))


//导航转换成路由
const menuToRoute = (menu)=>{
  if (!menu.component){
    return null
  }

  let  route = {
    name: menu.name,
    path: menu.path,
    meta: {
      icon: menu.icon,
      title: menu.title
    }
  }
  route.component = ()=> import('../views/' + menu.component + '.vue')
  return route
}

export default router
